package net.vinote.smartweb.service.util;

import net.vinote.smartweb.service.result.SmartResult;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

public class SmartOperationTransactionTemplate {
	@Autowired
	private TransactionTemplate transactionTemplate;

	public void operateWithTransaction(SmartResult<?> result, SmartServiceCallback callback) {
		operate(result, callback, true);
	}

	public void operateWithoutTransaction(SmartResult<?> result, SmartServiceCallback callback) {
		operate(result, callback, false);
	}

	private void operate(SmartResult<?> result, final SmartServiceCallback callback, boolean withTransaction) {
		try {
			callback.doCheck();

			callback.doPreOperate();

			if (withTransaction) {
				transactionTemplate.execute(new TransactionCallback<Object>() {
					public Object doInTransaction(TransactionStatus status) {
						callback.doOperate();
						return null;
					}

				});
			} else {
				callback.doOperate();
			}
			callback.doAfterOperate();
			result.setSuccess(true);
		} catch (Exception e) {
			result.setSuccess(false);
			e.printStackTrace();
		}
	}
}
